<template>
  <!-- 视频生成第二步 -->
  <div>
    <el-row>
      <el-col :span="24">
        <div class="themm-black themm-bg" style="padding-top: 0;">
          <div class="step-text">
            step3:视频生成
          </div>
          <div class="fragment-item" v-for="(item, index) in taskVideo.sequence" :key="index">
            <div style="flex: 1;">
              <div class="fragment-title">
                <span class="title">片段集合{{ index + 1 }}</span>
                <!-- {{ sss.length }}
                <el-tooltip :disabled="sss.length<20?true:false" class="item" effect="dark" :content="sss" placement="top">
                  <div class="fragment-title-text ellipsis" style="width: 300px;">{{ sss }}</div>
                </el-tooltip> -->
                <el-tooltip :disabled="item.caption.length<64?true:false" class="item" effect="dark" :content="item.caption" placement="top">
                  <div class="fragment-title-text ellipsis">{{ item.caption }}</div>
                </el-tooltip>
                <div class="fragment-title-icon">
                  <audio :ref="'music' + index" :key="index" :src="item.audio"></audio>
                  <div class="voice-play" @click="playVoice(item, index)">
                    <img class="play-img" src="@/assets/icons/play.png" alt="">
                  </div>
                </div>
              </div>
              <div class="fragment-content">
                <div class="swiper-containers">
                  <div class="swiper-wrapper">
                    <draggable
                      v-model="item.clips"
                      chosenClass="chosen"
                      forceFallback="true"
                      :group="{name: 'child', pull: false}"
                      animation="1000"
                      style="display: flex;"
                      @update="onEnd(item.clips,index, $event)"
                    >
                      <div v-for="(cell, subindex) in item.clips" class="swiper-slide">
                        <div style="display: flex;align-items: center;justify-content: center;">
                          <img class="gesture" src="@/assets/icons/gesture.png" alt="">
                          <video :controls="true" controlslist="noplaybackrate nodownload" :key="cell.videoClipId" disablePictureInPicture
                            oncontextmenu="return false" name="media" class="frame-img" style="width: 100%;" :poster="cell.thumbnail">
                            <source :src="cell.previewUrl" type="video/mp4">
                          </video>
                        </div>
                        <div class="frame-footer">
                          <el-button type="text" @click="handleTailor(cell)">裁剪</el-button>
                          <el-button type="text" @click="handleRemove(item, subindex)">移除</el-button>
                        </div>
                      </div>
                    </draggable>

                  </div>
                </div>
              </div>
            </div>

            <div class="fragment-btn">
              <el-button type="primary" class="primary-btn" size="mini" icon="el-icon-plus"
                @click="addVideoMaterial(index, item.caption)">添加</el-button>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="24" class="themm-black themm-bg">
        <div class="">
          <el-form :model="taskVideo" ref="taskVideo" size="small" :rules="rules" :hide-required-asterisk="true"
            :inline="true" label-width="100px">
            <el-col>
              <el-form-item label="视频标题：" prop="title">
                <el-input v-model="taskVideo.title" placeholder="请输入视频标题" clearable style="width:600px"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="语种：" prop="language">
                <el-select v-model="taskVideo.language" placeholder="请选择" clearable style="width: 100%">
                  <el-option v-for="dict in dict.type.language" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="分辨率：" prop="resolution">
                <el-select v-model="taskVideo.resolution" placeholder="请选择" clearable style="width: 100%">
                  <el-option v-for="dict in dict.type.resolution_ratio" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
              </el-form-item>
              <el-form-item label="滤镜：" prop="filter">
                <el-select v-model="taskVideo.filter" placeholder="请选择" clearable style="width: 100%">
                  <el-option v-for="dict in filterList" :key="dict.id" :label="dict.name" :value="dict.name" />
                </el-select>
              </el-form-item>
              <el-form-item label="背景音乐" prop="backgroundMusic">
                <el-select v-model="taskVideo.backgroundMusic" placeholder="请选择" clearable style="width: 100%">
                  <el-option v-for="dict in audioTemplate" :key="dict.id" :label="dict.description" :value="dict.url" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <div class="volume-footer">
      <el-button type="primary" class="green-btn" size="mini" @click="handlePrev">上一步</el-button>
      <el-button type="primary" class="reset-btn" size="mini" @click="resetform">重置当前</el-button>
      <el-button type="primary" class="primary-btn" size="mini" @click="createVideoNews">生成新闻</el-button>
    </div>
    <!-- 视频素材 -->
    <video-material ref="videoMaterial" @insertion="insertionList" />
    <!-- 视频裁剪 -->
    <tailor-video ref="tailorVideo" @insertion="insertion" />
  </div>
</template>

<script>
import draggable from "vuedraggable"
import { getFileTemplate, getFilter } from "@/api/content/task";
import { videoAggregate } from "@/api/content/algorithm";//算法接口表
import Preview from "./Preview";
import VideoMaterial from "./VideoMaterial";
import TailorVideo from "./TailorVideo";

export default {
  name: "Step2",
  components: {
    Preview,
    VideoMaterial,
    TailorVideo,
    draggable 
  },
  dicts: ['language', 'resolution_ratio', 'filter_image'],
  props: ['taskVideo'],
  data() {
    return {
      loading: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      activeName: 'first',
      swiperOptions: {
        // 配置选项，如滑动方向、自动播放、分页器等
      },
      form: {

      },
      rules: {
        title: [
          { required: true, message: '请输入视频标题', trigger: 'blur' },
        ],
        language: [
          { required: true, message: '请选择语种', trigger: 'blur' },
        ],
        resolution: [
          { required: true, message: '请选择分辨率', trigger: 'blur' },
        ],
        filter: [
          { required: true, message: '请选择滤镜', trigger: 'blur' },
        ],
        backgroundMusic: [
          { required: true, message: '请选择背景音乐', trigger: 'blur' },
        ],
      },
      checkList: [],
      retrieveList: [],
      tabIndex: 'private',
      volumeNum: 1,
      detail: {},
      swiper: null,
      fragment: [],
      frames: [], // 存储帧图片的数组
      audioTemplate: [],
      filterList: [],
      curFragmentIndex: {},//当前片段索引
      isPlay: false,
      group: {
        name: 'pageButton',
        pull: false,
        put: false
      },
      drag: false,
      sss:'文本超出范围才显示省略号,否则不显示省略号 3.浏览器原生实现,所以省略号位置显示刚好 但是缺点也是很直接,因为-webkit-line-clamp是一个不规范的属性,它没有出现在CSS规,文本超出范围才显示省略号,否则不显示省略号 3.浏超出范围才显示省略号,否则不显示省略号 3.浏览器原生实现,所以省略号位置显示刚好 但是缺点也是很直接,因为-webkit-line-clamp是一个不规范的属性,它没有出现在CSS规,文本超出范围才显示省略号,否则不显示省略号 '
    };
  },
  mounted() {
    this.getAudioTemplate()
    this.getFilter();
    this.getSwiper()
  },
  methods: {
    // 保存的数据回填
    setBackfill() {
      console.log(this.$store.state.user, 'vuex')
    },
    // 获取背景音乐
    async getAudioTemplate() {
      const { data: res } = await getFileTemplate('background_music');
      console.log(res);
      this.audioTemplate = res.map(n => {
        n.isPlaying = false;
        return n;
      });
    },
    // 获取滤镜
    async getFilter() {
      const { data: res } = await getFilter('filter_image');
      console.log(res);
      this.filterList = res;
    },
    getSwiper() {
      return
      this.swiper = new Swiper(".swiper-containers", {
        loop: false, // 无缝
        // autoplay: { //自动开始
        //     delay: 3000, //时间间隔
        //     disableOnInteraction: false, //*手动操作轮播图后不会暂停*
        // },
        autoplay: false,
        paginationClickable: true,
        slidesPerView: 8, // 一组三个
        spaceBetween: 6, // 间隔
        // 如果需要前进后退按钮
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        // 窗口变化,重新init,针对F11全屏和放大缩小,必须加
        observer: true,
        observeParents: true,
        // 如果需要分页器
        pagination: {
          el: '.swiper-pagination',
          clickable: true, // 分页器可以点击
        },
      })
    },

    // 添加视频素材
    addVideoMaterial(index, caption) {
      this.curFragmentIndex = index
      console.log(this.taskVideo)
      this.$refs.videoMaterial.show(this.taskVideo, caption)
    },
    // 素材裁剪插入
    insertion(item) {
      console.log(item)
      const obj = {
        name: item.preViewUrl,
        clip_time: [0, 50],
      }
      this.taskVideo.sequence[this.curFragmentIndex].clips.push(obj)
      this.getSwiper()
    },
    // 添加素材后回填
    insertionList(list) {
      console.log(this.taskVideo.sequence[this.curFragmentIndex].clips.length, 'this.taskVideo.sequence[this.curFragmentIndex].clips.length')
      const mergeList = [...this.taskVideo.sequence[this.curFragmentIndex].clips, ...list]
      if (mergeList.length > 8) {
        return this.$message.error('最多添加8个片段')

      }
      list.map(res => {
        // res.clip_time = [0, 50]
        this.taskVideo.sequence[this.curFragmentIndex].clips.push(res)
      })
      console.log(this.taskVideo.sequence, 'this.taskVideo.sequence')

      this.getSwiper()
    },
    extractFrames() {
      console.log('ssssssssssssssssss')
      const video = this.$refs.video;
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const { width, height } = video;

      canvas.width = width;
      canvas.height = height;

      const extractFrame = (time) => {
        if (video.paused || video.ended) return;
        ctx.drawImage(video, 0, 0, width, height);
        this.frames.push(canvas.toDataURL());
        setTimeout(() => {
          extractFrame(video.currentTime + 1 / video.framerate);
        }, 1000 / video.framerate);
      };

      video.addEventListener('play', () => {
        extractFrame(video.currentTime);
      });
    },
    // 上一步
    handlePrev() {
      this.$emit('changeStep', 1)
      // console.log(this.form)
      // this.$store.commit('SET_VIDEOMAKESTEP2', this.form)
      // this.$router.push({
      //   path: '/content/videoMake'
      // })
    },
    // 重置当前
    resetform() {
      this.taskVideo = {
        title: undefined,
        language: undefined,
        resolution: undefined,
        filter: undefined,
        backgroundMusic: undefined,
      };
      this.resetForm("taskVideo");
    },
    // 生成新闻
    async createVideoNews() {
      console.log(this.taskVideo)
      const params = {
        ...this.taskVideo,
        // audio: "http://123.249.84.255:9445/templates/audios/LHYS_B1.wav",
      }

      this.$refs["taskVideo"].validate(async valid => {
        if (valid) {
          this.openLoading();
          const { data } = await videoAggregate(params)
          this.$modal.msgSuccess('生成成功');
          this.$emit('resetform')
          this.$modal.closeLoading();
        }
      });

      // this.$router.push({
      //   path: '/content/task/list'
      // })
    },
    setVideoImg(url) {
      this.$nextTick(() => {
        // 创建视频
        let video = document.createElement('video')
        console.log(video)
        video.controls = 'controls'
        video.crossOrigin = 'anonymous'
        // 播放地址
        let source = document.createElement('source')
        source.src = url
        source.type = 'video/mp4'
        video.appendChild(source)
        // 这很重要
        video.currentTime = 1
        // 当前帧的数据已加载
        video.addEventListener('loadeddata', () => {
          // 创建画布
          var canvas = document.createElement('canvas')
          canvas.width = video.videoWidth * 0.5
          canvas.height = video.videoHeight * 0.5
          canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
          // 转码添加
          var img = document.createElement('img')
          let src = canvas.toDataURL('image/png')
          img.src = src
          // 给特定vue节点添加
          this.$refs['video-img-xxx'].appendChild(img)
        })
      })
    },
    // 去裁剪
    handleTailor(item) {
      this.$refs['tailorVideo'].show(item)
    },
    // 删除片段
    handleRemove(item, index) {
      console.log(index)
      console.log(item)
      item.clips.splice(index, 1)
    },
    async playVoice(item, index) {
      // const audio = this.$refs['music' + index][0];
      // console.log(audio, 'audio');
      const that = this
      console.log(item, '播放状态', this.isPlay, 'this.isPlay');
      // audio.play();
      var audio = document.createElement("audio");
      audio.src = item.audio
      if (this.isPlay) {
        return this.$modal.msgSuccess('正在播放中');
      }
      audio.play();
      this.isPlay = true
      audio.addEventListener("ended", function () {
        console.log("播放结束");
        that.isPlay = false
      })
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在生成，请稍候！");
    },
    onStart(index){
      this.curFragmentIndex = index
    },
    onEnd(list,i,evt) {
      this.$nextTick(() => {
        this.$set(this.taskVideo.sequence[i],'clips',list)
      })
    },
  },
};
</script>
<style scoped lang="scss">
.step-text {
  color: #fff;
  font-size: 14px;
  padding: 20px;
}

.voice-select {
  padding: 0 65px;
  position: relative;
}

.swiper-slide {
  width: 180px;
  padding: 0 15px;
  border-radius: 8px;
}

.frame-img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.frame-footer {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}

.voice-btn {
  background: rgba(255, 255, 255, .1);
  color: #fff;
  padding: 10px;
  border-radius: 0 0 8px 8px;
  font-size: 14px;
  text-align: center;
  cursor: pointer;
}

.swiper-button-next,
.swiper-button-prev {
  background: rgba(255, 255, 255, .1);
  border-radius: 8px;
  color: #fff;
  font-size: 14px;
  padding: 73px 25px;
  top: 24px;
  opacity: 1;
  right: 0;
}

.swiper-button-prev {
  left: 0;
}

.swiper-button-next:after,
.swiper-button-prev:after {
  font-size: 18px;
}



.volume-footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: flex-end;
  background: rgba(255, 255, 255, .1);
  margin-top: 20px;
  padding: 20px;
  // margin-left: -30px;
  // margin-right: -30px;
}

.app-container {
  padding-bottom: 0;
}

.bg {
  background-image: url("../../../../assets/images/content_bg.png");
  background-size: 25%;
  background-repeat: no-repeat;
  background-position: top right;
}

.themm-bg {
  padding-bottom: 20px;
}

.fragment-item {
  display: flex;
  color: #fff;
  align-items: center;
  // justify-content: space-between;
  margin: 0 20px;

  .fragment-content {
    background: rgba(255, 255, 255, .1);
    padding: 20px 0;
    // height: 180px;
  }

  .fragment-title {
    display: flex;
    font-size: 14px;
    margin: 10px 0;

    .title {
      width: 90px;
      color: rgba(255, 255, 255, .6);
      margin-right: 20px;
    }
  }

  .fragment-btn {
    width: 200px;
    padding-left: 20px;
  }

  .fragment-title-text {
    width: 900px;
  }

  .fragment-title-icon {
    width: 50px;

    .voice-play {
      margin-left: 10px;
      cursor: pointer;

      .play-img {
        width: 20px;
        height: 20px;

        &.active {
          animation: play 1s linear infinite;
        }

      }
    }
  }
}
.gesture{
  width: 18px;
  height: 18px;
  margin-right: 5px;
}
video::-webkit-media-controls-volume-control-container {
  display: none !important;
}

video::-internal-media-controls-overflow-button {
  display: none !important;
}
</style>
